package org.example.core;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.bus.event.Destination;
import org.springframework.cloud.bus.event.PathDestinationFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class BusEventServiceImpl implements BusEventService {

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Resource
    private BusProperties busProperties;

    @Resource
    private PathDestinationFactory pathDestinationFactory;

    @Override
    public Boolean publishRouteEvent(String route) {
        System.out.println("id: " + busProperties.getId());
//        Destination destination = pathDestinationFactory.getDestination(String.format("%s:**", busProperties.getId()));
        Destination destination = pathDestinationFactory.getDestination("**");
        RouteEvent routeEvent = new RouteEvent(busProperties.getId(), busProperties.getId(), destination, route);
        try {
            log.info("Bus start publishing event");
            applicationEventPublisher.publishEvent(routeEvent);
            log.info("Bus publish event success");
            return true;
        } catch (Exception e) {
            log.error("Bus publish event fail:",e);
        }
        return false;
    }
 }